package com.ruoyi.web.aop;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.maode.domain.dto.ApproveRequestDTO;
import com.ruoyi.maode.domain.entity.Part;
import com.ruoyi.maode.domain.vo.TaskVO;
import com.ruoyi.maode.service.PartService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.util.QyWx.SendQyWxMsgUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.trie.PatriciaTrie;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 动态获取创建审批流程操作的接口
 * @author zhangwenqiang
 */
@Component
@Aspect
@Slf4j
public class ApproveAop {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private PartService partService;

    @Value("${qywx.url}")
    private String qywxUrl;

    @Value("${server.url}")
    private String serverUrl;
    /**
     * 切点定义，适用于任何返回类型和任何参数的generateReport方法
     */
    @Pointcut("execution(* com.ruoyi.maode.controller.PartMeasureController.generateReport(..))")
    public void pointCut() {}


    @Pointcut("execution(* com.ruoyi.maode.controller.FlowableController.approve(..))")
    public void approvePointCut() {}


    /**
     * 创建流程成功后才会执行此方法
     */
    @After("pointCut()")
    public void addApprove() {
        System.out.println("执行完成，afterReturn 被触发");;
        List<Task> tasks = taskService.createTaskQuery().orderByTaskCreateTime().desc().list();
        // 获取最新的任务
        if (!CollectionUtils.isEmpty(tasks)) {
            Task task = tasks.get(0);
            TaskVO vo = new TaskVO();
            Map<String, Object> processVariables = taskService.getVariables(task.getId());
            vo.setTaskId(task.getId());
            vo.setProcessInstanceId(task.getProcessInstanceId());
            vo.setProcessVariables(processVariables);
            vo.setTaskName(task.getName());
            // 获取规格描述
            Part part = partService.getOne(new LambdaQueryWrapper<Part>()
                    .eq(Part::getPartCode, String.valueOf(vo.getProcessVariables().get("partCode")))
                    .eq(Part::getIsDelete,Constants.CONSTANTS_ZERO));
            // 发送企业微信品质部长
            try {
                SendQyWxMsgUtils.sendText( vo.getProcessVariables().get("partReportUrl") + "",
                        vo.getProcessVariables().get("partCode") + "",vo.getProcessVariables().get("partBatchCode") + "",part.getPartDescription(),qywxUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 执行审批后获取最新数据推送给对应人员
     */
    @Around("approvePointCut()")
    public Object sendApproveMsg(ProceedingJoinPoint joinPoint){
        // 获取目标方法的所有参数
        Object[] args = joinPoint.getArgs();
        // 可以遍历所有参数，查看其类型和值
        ApproveRequestDTO approveRequestDTO = new ApproveRequestDTO();
        for (Object arg : args) {
            BeanUtils.copyProperties(arg,approveRequestDTO);
        }
        SysUser sysUser = userService.selectUserById(approveRequestDTO.getAssignee());
        Map<String, Object> variables = taskService.getVariables(approveRequestDTO.getTaskId());

        // 获取产品信息
        Part part = partService.getOne(new LambdaQueryWrapper<Part>()
                .eq(Part::getPartCode, String.valueOf(variables.get("partCode")))
                .eq(Part::getIsDelete,Constants.CONSTANTS_ZERO));

        // 继续执行目标方法并获取返回值
        Object returnValue = null;
        try {
            returnValue = joinPoint.proceed();
            HistoricProcessInstance instance = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(approveRequestDTO.getProcessInstanceId())
                    .singleResult();
            // 如果审批没有完成触发邮件发送
            if (!Constants.OK_PROCESS_ID.equals(instance.getEndActivityId()) && !"审批完成".equals(instance.getBusinessStatus())) {
                SendQyWxMsgUtils.sendText( variables.get("partReportUrl") + "",
                        variables.get("partCode") + "",variables.get("partBatchCode") + "",
                        part.getPartDescription(),sysUser.getNickName() ,qywxUrl);
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        // 返回目标方法的执行结果
        return returnValue;
    }
}
